import React from "react";
import { LogoutOutlined, UserOutlined } from "@ant-design/icons";
import { Avatar, Menu, Spin } from "antd";
import { history, useAuth } from "ice";
import HeaderDropdown from "../HeaderDropdown";
import styles from "./index.module.css";
import store from "@/store";
import request, { handleRes } from "@/utils/request";
import type { ApiResponse } from "@/pages/system/user/types";
import { loginApi } from "@/pages/login/api";

export interface GlobalHeaderRightProps {
  menu?: boolean;
}

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
  const [userState, userDispatchers] = store.useModel("user");
  const [auth, setAuth] = useAuth();

  const onMenuClick = async (event: { key: string }) => {
    const { key } = event;

    if (key === "logout") {
      try {
        // 调用退出登录接口
        await handleRes({
          api: loginApi.logout,
          success: {
            msg: true,
            callBack: () => {
              
              // 清除本地存储
              localStorage.removeItem("token");
              localStorage.removeItem("userInfo");

              // 清除用户状态
              // userDispatchers.clearUserInfo();
              
              // 设置登录状态为false
              // setAuth({ isLogin: false });

              // 跳转到登录页
              history?.push("/login");
            }
          },
        });
      } catch (error) {
        console.error("Logout failed:", error);
      }
    }
  };

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!userState.currentUser) {
    return loading;
  }

  const menuItems = [
    {
      key: "center",
      icon: <UserOutlined />,
      label: "个人中心",
    },
    {
      key: "logout",
      icon: <LogoutOutlined />,
      label: "退出登录",
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        items: menuItems,
        onClick: onMenuClick,
      }}
    >
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          className={styles.avatar}
          src={userState.currentUser.avatar}
          alt="avatar"
        />
        <span className={`${styles.name} anticon`}>
          {userState.currentUser.username}
        </span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
